package com.bdth.weget.net.controller;

import com.bdth.weget.common.CommonResult;
import com.bdth.weget.common.MessageResult;
import com.bdth.weget.net.NetServer;
import com.bdth.weget.net.vo.ServerStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.ServerSocket;

@Controller
@RequestMapping("/server")
public class ServerCtrlController {
    @Autowired
    private NetServer netServer;

    /**
     * 查询服务器是否启动
     * @param ip
     * @param port
     * @return
     */
    @RequestMapping("status")
    @ResponseBody
    public CommonResult<ServerStatus> serverIsStart(@RequestParam(required = false) String ip,
                                                    @RequestParam(required = false) Integer port){
        ServerStatus bean = new ServerStatus();
        if(ip==null|| ip.equals(""))
            ip = "127.0.0.1";
        if(port==null || port==0)
            port = 5556;
        bean.setIp(ip);
        bean.setPort(port);
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(port);
        } catch (IOException e) {
            bean.setStatus(true);
            return CommonResult.success(bean);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
        bean.setStatus(false);
        return CommonResult.success(bean);
    }

    @RequestMapping("start")
    @ResponseBody
    public MessageResult startServer(){
        try{
            netServer.startd();
        }catch (Exception e){
            return MessageResult.getError("500","服务器启动失败！");
        }
        return MessageResult.getSuccess("服务器启动成功");
    }

    @RequestMapping("stop")
    @ResponseBody
    public MessageResult stopServer(){
        try{
            netServer.shutdown();
        }catch (Exception e){
            return MessageResult.getError("500","服务器停止失败！");
        }
        return MessageResult.getSuccess("服务器停止成功");
    }
}
